#!/usr/bin/env bash
# shellcheck disable=SC2034
backVersionCount=1
baseDir=$(pwd)
# shellcheck disable=SC2034
# shellcheck disable=SC2012
jars=$(ls -l history-jar/ | awk '{print $9}')
# shellcheck disable=SC2190
# shellcheck disable=SC2206
for i in ${jars} ; do jars2=${jars2},${i};done
OLD_IFS="$IFS"
IFS=","
# shellcheck disable=SC2206
jarArray=(${jars2:1})
IFS="$OLD_IFS"
# shellcheck disable=SC2068
for((i=0;i<${#jarArray[@]};i++)){
  for((j=0;j<${#jarArray[@]}-1;j++)){
    date0="${jarArray[j]:17:10} ${jarArray[j]:28:8}";
    date1="$(date -d "${date0}" +%s)";
    date2="${jarArray[j+1]:17:10} ${jarArray[j+1]:28:8}";
    date3="$(date -d "${date2}" +%s)";
    if [[ ${date1} -lt ${date3} ]]; then
      # shellcheck disable=SC2154
      tmp=${jarArray[j]}
      jarArray[j]=${jarArray[j+1]}
      jarArray[j+1]=$tmp
    fi
  }
}
echo "软件历史版本共计 -> "${#jarArray[@]}
for((i=0;i<${#jarArray[@]};i++)){
  echo "[${i}]-""${jarArray[i]}"
}
if [[ -n "${1}" ]]; then
  backVersionCount="${1}";
  [[ ${1} -gt ${#jarArray[@]} ]] && echo "[回退版本数量大于存在的版本数量,回退失败...]" && exit 1
  # shellcheck disable=SC2236
  echo "${1}"|[ ! -n "$(sed -n '/^[0-9][0-9]*$/p')" ] && echo "第一个参数为回退版本个数,参数错误..." && exit 2
fi

echo "将回退${backVersionCount}个版本启动[${jarArray[${backVersionCount}]}]..."
# shellcheck disable=SC2162
read -p "是否继续? [y/n]>" isContinue
# shellcheck disable=SC1073
# shellcheck disable=SC1072
# shellcheck disable=SC1020
# shellcheck disable=SC1009
if [[ "${isContinue}" == "y" || "${isContinue}" == "" ]]; then
  cp -f "${baseDir}"/history-jar/"${jarArray[${backVersionCount}]}" "${baseDir}"/inspect-line-2.0.jar
  pid=$(jps | grep inspect-line-2.0.jar | awk '{print $1}')
  [[ -n ${pid} ]] && kill -9 "${pid}"
  # shellcheck disable=SC2174
  [[ ! -e "${baseDir}"/history-log/ ]] && mkdir -m 755 -p "${baseDir}"/history-log
  # shellcheck disable=SC2046
  [[ -e "${baseDir}"/inspect-line-2.0.log ]] && cp "${baseDir}"/inspect-line-2.0.log "${baseDir}"/history-log/inspect-line-2.0-$(date +%Y-%m-%d_%H:%M:%S).log
  export MALLOC_ARENA_MAX=1
  nohup java -jar -server -Xms2048m -Xmx2048m -Xmn1024m -Xss512k -Dsun.zip.disableMemoryMapping=true "${baseDir}"/inspect-line-2.0.jar --spring.profiles.active=dev-110 >"${baseDir}"/inspect-line-2.0.log 2>&1 &
  echo "Process $! start Success!"
  tailf "${baseDir}"/inspect-line-2.0.log
fi